package com.hst.capacity.infra.web.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Configuration
public class RestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        RestTemplate template = builder.setConnectTimeout(Duration.ofSeconds(5))
                .messageConverters().build();
        /* 添加JSON转换支持的媒体类型 */
        for (HttpMessageConverter c : template.getMessageConverters()) {
            if (c instanceof MappingJackson2HttpMessageConverter) {
                ((MappingJackson2HttpMessageConverter) c)
                        .setSupportedMediaTypes(
                                Arrays.asList(
                                        MediaType.parseMediaType("text/javascript"),
                                        MediaType.APPLICATION_JSON
                                )
                        );
            }
        }
        return template;
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter(){
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String s) {
                return LocalDateTime.parse(s);
            }
        };
    }
}
